package cn.rkylin.oms.order.adapter;

import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.order.domain.Order;
import cn.rkylin.oms.order.service.OrderServiceImpl;
import cn.rkylin.oms.order.vo.TaoBaoOrder;
import cn.rkylin.oms.sysOrder.service.SysOrderServiceImpl;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.warehouse.shiporder.request.RequestTradeOfflineSend;
import cn.rkylin.oms.warehouse.shiporder.service.ShiporderServiceImpl;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: jipengcheng
 * @Created: 2018-2-27
 */
@Service("vipOrderVisitor")
public class VipOrderVisitor extends OrderVisitor {

    @Autowired
    private LogUtil logUtil;

    @Value("${oms.address}")
    private String omsAddres;

    @Autowired
    private ShiporderServiceImpl shiporderServiceImpl;

    @Autowired
    private SysOrderServiceImpl sysOrderServiceImpl;

    @Autowired
    OrderServiceImpl orderServiceImpl;

    @Override
    public int getOrderList(Date startTime, Date endTime, Map<String, String> paramMap) {
        return 0;
    }

    @Override
    public Order getOrder(String orderNumber, Map<String, String> paramMap) {
        return null;
    }

    @Override
    protected void saveOrder() {

    }

    @Override
    public List<Order> getOrderList(Map<String, String> paramMap) {
        return null;
    }

    @Override
    public Map<String, Object> getOrderObject(Map<String, Object> paramMap) {
        return null;
    }

    @Override
    public void getOrderObjectList(Map<String, Object> paramMap, Integer startRow, Integer endRow, List<TaoBaoOrder> loopList) {

    }

    @Override
    public Map<String, Object> getOrderObject(String tid, Shop shopVO) {
        return null;
    }

    /**
     * 平台发货
     *
     * @param paramMap return 结果Map
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> consign(Map<String, Object> paramMap) throws Exception {

        Map<String, Object> returnMap = new HashMap<String, Object>();

        ShopVO shopVO = (ShopVO) paramMap.get("shop");
        // 查询需要平台发货的信息
        List<ShiporderVO> shipOrderList = shiporderServiceImpl.selectByShopVoShipOrderConsign(shopVO);
        // 轮询发货
        for (int i = 0; i < shipOrderList.size(); i++) {
            ShiporderVO shiporderVO = shipOrderList.get(i);
            // 如果是合并的订单
            if (shiporderVO.getTradeCode().indexOf(",") != -1) {
                String[] tradeCodeSplit = shiporderVO.getTradeCode().split(",");
                for (String temp : tradeCodeSplit) {

                    // 平台发货
                    consignApi(temp, shopVO, shiporderVO);
                }
                continue;
            }

            // 非合并订单
            // 平台发货
            consignApi(shiporderVO.getTradeCode(), shopVO, shiporderVO);
        }
        returnMap.put("success", "true");
        returnMap.put("msg", "");
        return returnMap;
    }

    /**
     * 平台发货 - 调用xvp平台api
     * @param tradeCode
     * @param shopVO
     * @param shiporderVO
     * @throws Exception
     */
    private void consignApi(String tradeCode, ShopVO shopVO, ShiporderVO shiporderVO) throws Exception {

        // 拆包发货相关业务 start
        // 获取平台订单信息
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("ecTradeCode", tradeCode);
        reqMap.put("shopId", shopVO.getShopId());
        cn.rkylin.oms.order.domain.EcTrade ecTrade = orderServiceImpl.selectByEcTradeCodeAndShopIdEcTrade(reqMap);
        if (ecTrade == null) {
            return;
        }
        // 判断平台订单状态
        // EC_WAIT_BUYER_PAY(等待买家付款)
        // EC_WAIT_SELLER_SEND(等待卖家发货,即:买家已付款) EC_TRADE_PARTIALLY_SEND(交易部分发货)
        // EC_TRADE_ALL_SEND(交易全部发货) EC_TRADE_FINISHED(交易成功)
        // EC_TRADE_CANCELED(交易取消)
        if ("EC_TRADE_FINISHED".equals(ecTrade.getEcTradeStatus())
                || "EC_TRADE_CANCELED".equals(ecTrade.getEcTradeStatus())) {
            // 保存数据
            consignSaveData(shopVO, shiporderVO, false);
            return;
        }
        // 拆包发货相关业务 end

        // 调用平台发货接口
        cn.rkylin.oms.warehouse.shiporder.request.RequestTradeOfflineSend requestTradeOfflineSend = null;
        requestTradeOfflineSend = new RequestTradeOfflineSend();
        requestTradeOfflineSend.setEcTradeCode(tradeCode);
        requestTradeOfflineSend.setLgstCode(shiporderVO.getLgstCode());
        requestTradeOfflineSend.setLgstName(shiporderVO.getLgstName());
        requestTradeOfflineSend.setLgstNo(shiporderVO.getLgstNo());
        Map<String, String> execMap = shiporderServiceImpl.pushOfflineSend(shopVO.getShopId(), requestTradeOfflineSend);
        if (execMap.containsKey("success")) {
            // 成功
            if ("y".equals(execMap.get("success"))) {
                // 保存数据
                consignSaveData(shopVO, shiporderVO, true);
            }
            // 失败
            if ("n".equals(execMap.get("success"))) {
                String errMsg = execMap.get("msg");
                // 记录日志发货单
                logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "consign",
                        DateUtil.getCurrentDateStr() + "  发货单: 唯品会系统自动平台发货任务, 发货失败: " + errMsg));
            }
        } else {
            // 记录日志发货单
            logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "consign",
                    DateUtil.getCurrentDateStr() + "  发货单: 唯品会系统自动平台发货任务, 发货失败: " + "远程连接错误或请求不正确"));
        }
    }

    /**
     * 平台发货 - 数据保存
     *
     * @author jipengcheng
     * @param shiporderVO
     * @throws Exception
     */
    private void consignSaveData(ShopVO shopVO, ShiporderVO shiporderVO, Boolean isUpdateSysOrder) throws Exception {

        if (isUpdateSysOrder) {
            // 更新订单
            cn.rkylin.oms.sysOrder.vo.SysOrderVO sysOrderVOUpdate = new SysOrderVO();
            sysOrderVOUpdate.setTradeCode(shiporderVO.getTradeCode());
            sysOrderVOUpdate.setShopId(shopVO.getShopId());
            sysOrderVOUpdate.setConsignTime(new Date());
            sysOrderServiceImpl.updateByPrimaryKeySelectiveSysOrder(sysOrderVOUpdate);
        }

        // 更新发货单
        cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO shiporderVOUpdate = new ShiporderVO();
        shiporderVOUpdate.setShiporderCode(shiporderVO.getShiporderCode());
        shiporderVOUpdate.setConsignStatus("y");
        shiporderVOUpdate.setConsignTime(cn.rkylin.oms.common.utils.DateUtil.formatDate(new Date()));
        shiporderServiceImpl.updateByPrimaryKeySelectiveShipOrder(shiporderVOUpdate);

        // 记录日志发货单
        logUtil.info(new DBLog(shiporderVO.getShiporderCode(), "", "consign",
                DateUtil.getCurrentDateStr() + "  发货单: 唯品会系统自动平台发货任务, 发货成功!"));
    }
}
